import { Button, message, Space, } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, useEffect, } from 'react';
import { getDvaApp, history, } from 'umi';
import ProForm, {
    ModalForm,
    ProFormDigit,
    ProFormSelect,
} from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import { BatchUpdateType, CabinetCellList } from '@/services/cabinet';
import { cellTypes } from '@/utils/common';
import $utils from '@/utils/utils';

const CellType: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    const formRef = useRef<ProFormInstance>();
    const [cur_id, setCur_id] = useState<string>();
    const [cabCode, setCabCode] = useState<string>();   // TODO: 副柜
    const [cellTypeData, setCellTypeData] = useState<any>([]);    // TODO 格口数据data
    const [cellCount, setCellCount] = useState<number>(0);      // TODO 格口总数
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);    // TODO 已选择格口ids
    const [maxCount, setMaxCount] = useState<number>(99);   // TODO 格口数最大限制

    const restFormRef = useRef<ProFormInstance>();
    const [modalVisible, setModalVisible] = useState<boolean>(false);

    const l_state: any = history.location.state;
    if (!cur_id && !l_state) {
        history.push('/BasicConfig/Cabinet');
    }

    const id: string = l_state?.data?.id || '';
    //  同path更新,只更新state时，通过id重新请求数据
    if (l_state && id && (!cur_id || cur_id !== id)) {
        setCur_id(id);
    }
    else if (l_state && !id && cur_id !== id) {
        setCur_id('');
    }

    const isCreate: boolean = l_state?.status === 'create';
    const isUpdate: boolean = l_state?.status === 'update';

    useEffect(() => {
        l_state?.data?.code && setCabCode(l_state?.data?.code);
        // console.log(l_state);
        const getCellData = async () => {
            try {
                const msg = await CabinetCellList({
                    cabId: l_state?.data?.cabId,
                    slaveId: cur_id,
                    pageSize: 1000,
                    normal: 2
                });
                if (msg.code === 0) {
                    setCellCount(msg.body.count);
                    setCellTypeData(msg.body.list);
                    formRef && formRef.current?.resetFields();
                    return;
                }
            } catch (error) {
                message.error(`${error}`);
            }
        };

        //  TODO: 根据柜体硬件版本以及主板类型设置格口限制
        if (+l_state?.imeiData?.hwareVersion > 4) {
            l_state?.imeiData?.mainboard === 2 ? setMaxCount(32) : setMaxCount(50);
        } else if (+l_state?.imeiData?.hwareVersion > 0) {
            setMaxCount(22);
        }

        if (!cur_id) {
            setCellCount(l_state?.data?.cellList?.length || 0);
            setCellTypeData(l_state?.data?.cellList || []);
            formRef && formRef.current?.resetFields();
        } else {
            isUpdate && getCellData();
        }
    }, [cur_id]);

    const latticeType_columns: ProColumns<any>[] = [
        {
            title: '格口编号',
            align: 'center',
            dataIndex: 'desc',
            width: '100px',
            render: (text: any, record: any) => (
                <div>{record.desc}格口</div>
            )
        },
        {
            title: '格口类型',      // 格口类型 10901 大; 10902 中; 10903 小;10904 超小;10911 超大
            dataIndex: 'type',
            align: 'center',
            width: '100px',
            valueType: 'select',
            fieldProps: {
                options: cellTypes,
            }
        },
    ];

    const updateCellTypeData = (count: number) => {
        let newCellTypeData: any = [].concat(cellTypeData);
        if (count > cellTypeData.length) {
            const newCount = count - cellTypeData.length;
            [...new Array(newCount)].map((item: any, index: number) => {
                const data = {
                    desc: `${cabCode}${cellTypeData.length + index + 1}`,
                    type: 10903,
                    status: 11101
                };
                newCellTypeData.push(data);
            });
        }
        else {

            newCellTypeData = newCellTypeData.splice(0, count);
        }
        setCellTypeData(newCellTypeData);
    };

    // 新增的副柜，没有副柜id的保存操作
    const saveNewCabCellType = () => {
        const newCabCellData = [].concat(l_state?.cellData);
        const bigger = cellTypeData.filter((item: any) => item.type === 10911);
        const big = cellTypeData.filter((item: any) => item.type === 10901);
        const middle = cellTypeData.filter((item: any) => item.type === 10902);
        const small = cellTypeData.filter((item: any) => item.type === 10903);
        const tiny = cellTypeData.filter((item: any) => item.type === 10904);

        newCabCellData.map((item: any) => {
            if (item.code === cabCode) {
                item.cellList = cellTypeData;
                item.cellNum = cellTypeData.length;
                item.bigger = bigger.length;
                item.big = big.length;
                item.middle = middle.length;
                item.small = small.length;
                item.tiny = tiny.length;
            }
        });
        handleBack(newCabCellData);
    };

    // 编辑设置原有副柜的格口类型
    const saveCellTypeById = async () => {
        const cabId = l_state?.data?.cabId;
        const list: any = [];
        cellTypeData.map((item: any) => {
            list.push({
                id: item.cellId,
                type: item.type,
            });
        })
        const params = {
            cabId: cabId,
            list: JSON.stringify(list),
        };
        // 格口类型设置
        try {
            const msg = await BatchUpdateType(params);
            if (msg.code === 0) {
                // 有ID也将本地数据传回编辑页面
                message.success('操作成功', () => {
                    saveNewCabCellType();
                })
                return;
            }
        } catch (error) {
            message.error(`${error}`);
        }
    };

    // 返回编辑/新建柜体页面
    const handleBack = (cellData: any) => {
        // 设置当前tab对象
        const newTab = {
            name: isCreate ? `新建柜体` : `编辑柜体${l_state?.data.code}`,
            path: '/BasicConfig/Cabinet/detail',
            state: {
                status: l_state?.status,
                data: {
                    id: l_state?.data?.cabId,
                },
                cabDetail: l_state?.cabDetail,
                cellData: cellData,
            }
        };
        // 设置当前tab对象
        $utils.setNewTab(dispatch, newTab);
        $utils.addTab(dispatch, newTab)
        history.push({
            pathname: '/BasicConfig/Cabinet/detail',
            state: {
                status: l_state?.status,
                data: {
                    id: l_state?.data?.cabId
                },
                cabDetail: l_state?.cabDetail,
                cellData: cellData,
            }
        });
    };

    const handleUpdateCellType = (values: any) => {
        try {
            const newCellType = values.type;
            const newCellTypeData: any = JSON.parse(JSON.stringify(cellTypeData));
            selectedRowKeys.map(item => {
                newCellTypeData.forEach((j: any) => {
                    if (j.desc === item) {
                        if (j.status !== 11101) {
                            throw new Error('选中的格口有占用的格口，不允许修改类型');
                        } else {
                            j.type = newCellType;
                        }
                    }
                })
            });
            setCellTypeData(newCellTypeData);
            setSelectedRowKeys([]);
        } catch (err: any) {
            message.warning(`${err?.message}`);
        }
    };

    return (
        <PageContainer>
            <ProCard style={{ marginTop: 8 }} gutter={8} >
                <ProForm layout={'horizontal'} submitter={false}>
                    <ProForm.Group>
                        <ProFormDigit
                            label="格口数量"
                            min={0}
                            disabled={!!cur_id}
                            max={maxCount}
                            fieldProps={{
                                precision: 0,
                                value: cellCount,
                                onChange: (value: number | string) => {
                                    setCellCount(+value);
                                },
                            }}
                        />
                        {!cur_id && <Button type="primary" disabled={cellCount === cellTypeData.length} onClick={() => {
                            updateCellTypeData(cellCount);
                        }}>确定</Button>}
                    </ProForm.Group>
                </ProForm>
                <Button type="primary" style={{ marginBottom: 26 }} disabled={selectedRowKeys.length === 0} onClick={() => {
                    setModalVisible(true);
                }}>设置格口类型</Button>
                <ProTable
                    rowKey="desc"
                    search={false}
                    tableAlertRender={false}
                    pagination={false}
                    toolBarRender={false}
                    columns={latticeType_columns}
                    dataSource={cellTypeData}
                    rowSelection={{
                        // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                        // 注释该行则默认不显示下拉选项
                        selectedRowKeys: selectedRowKeys,
                        onChange: (newSelectedRowKeys: React.Key[]) => {
                            setSelectedRowKeys(newSelectedRowKeys);
                        }
                    }}
                />
                <Space style={{ marginTop: 18 }}>
                    <Button type="default" onClick={() => {
                        handleBack(l_state?.cellData);
                    }}>取消</Button>
                    <Button type="primary" onClick={async () => {
                        if (!cur_id) {
                            saveNewCabCellType();
                        } else {
                            saveCellTypeById();
                        }
                    }}>保存</Button>
                </Space>
            </ProCard>

            <ModalForm
                title="设置格口类型"
                formRef={restFormRef}
                modalProps={{
                    open: modalVisible,
                    onCancel: () => {
                        setModalVisible(false);
                    }
                }}
                width={360}
                layout={'horizontal'}
                onFinish={async (values) => {
                    handleUpdateCellType(values);
                    setModalVisible(false);
                    return true;
                }}
            >
                <ProFormSelect
                    name="type"
                    label="格口类型"
                    placeholder="请选择格口类型"
                    rules={[{ required: true, }]}
                    fieldProps={{
                        options: cellTypes
                    }}
                />
            </ModalForm>
        </PageContainer >
    );
};

export default CellType;
